import requests
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
import os,re
from selenium.webdriver.edge.options import Options
import parsel

save_dir = '日月同错'
if save_dir not in os.listdir('./'):
    os.mkdir(save_dir)
    
    
url = 'https://ac.qq.com/Comic/ComicInfo/id/644371'
headers = {
    'User-Agent' : 'Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52',
}
response = requests.get(url=url,headers=headers)
response.encoding = "utf-8"
selector = parsel.Selector(response.text)
href_list = selector.xpath('//ol[@class="chapter-page-all works-chapter-list"]/li/p/span/a/@href').getall()
href_name = selector.xpath('//ol[@class="chapter-page-all works-chapter-list"]/li/p/span/a/text()').getall()
href_list = ['https://ac.qq.com' + item for item in href_list]
href_list_0 = href_list[79:-15]
href_name_0 = href_name[79:-15]
for href,name in zip(href_list_0,href_name_0):
    #print(href,name)
    name = name.strip()
    #new_title = re.sub(r'[\/:*?"<>|]','',name)
    print(name)
    chapter_save_dir = os.path.join(save_dir, name)
    if name not in os.listdir(save_dir):
             os.mkdir(chapter_save_dir)
    #print(href,name)
    edge_options = Options()
    edge_options.add_argument('--headless')
    #edge_options.add_argument('--disable-gpu')
    driver = webdriver.Edge(options=edge_options)
    driver.get(href)
    time.sleep(3)
    targets = driver.find_elements(By.CSS_SELECTOR,'#comicContain > li > img')
    count = 0
    for target in targets:
        driver.execute_script("arguments[0].scrollIntoView()",target)
        time.sleep(3.5)
        img_url = target.get_attribute("src")
        Name = '%03d.jpg' % (count + 1)
        pic_save_path = os.path.join(chapter_save_dir, Name)
        img_data = requests.get(url=img_url).content
        with open(pic_save_path  , mode='wb') as f:
            f.write(img_data)
            count += 1
            print('保存完成：', Name)
    print('保存-----完成：',name)
    driver.quit()
 